package com.hibase.core.web.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 描述:
 *
 * @author li-wei-hua
 * @date 2020-09-07 16:04
 */
public class ShaUtils {

    // 加密算法SHA-256
    public final static String HASH_ALGORITHM_256 = "SHA-256";

    // 加密算法SHA-256
    public final static String HASH_ALGORITHM_1 = "SHA-1";

    // 加密算法SHA-256
    public final static String HASH_ALGORITHM_224 = "SHA-224";

    // 加密算法SHA-256
    public final static String HASH_ALGORITHM_384 = "SHA-384";

    // 加密算法SHA-256
    public final static String HASH_ALGORITHM_512 = "SHA-512";

    // 循环次数
    public final static int HASH_ITERATIONS = 32;

    /**
     * 生成加密字符串
     */
    public static String shaDigest(String algorithmName, Object source, Object salt, int hashIterations) {

        // todo 加密算法需要重新搞
//        return new SimpleHash(algorithmName, source, salt, hashIterations).toString();
        return null;
    }

    /**
     * 生成加密字符串
     */
    public static String shaDigest(Object source, Object salt) {

//        return new SimpleHash(HASH_ALGORITHM_256, source, salt, HASH_ITERATIONS).toString();
        return getSHA256String((String)source,(String)salt);
    }


    /**
     * 用java原生的摘要实现SHA256加密
     *
     * @param str 加密前的报文
     * @return
     */
    public static String getSHA256String(String source, String salt) {
        String encodeStr = "";
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");

            if (salt != null) {
                messageDigest.reset();
                messageDigest.update(salt.getBytes());
            }

            byte[] hashed = messageDigest.digest(source.getBytes());
            int iterations = HASH_ITERATIONS - 1;

            for(int i = 0; i < iterations; ++i) {
                messageDigest.reset();
                hashed = messageDigest.digest(hashed);
            }

//            messageDigest.update(str.getBytes("UTF-8"));
            encodeStr = byte2Hex(hashed);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
//        catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
        return encodeStr;
    }

    /**
     * byte[]转为16进制
     *
     * @param bytes
     * @return
     */
    private static String byte2Hex(byte[] bytes) {
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            String temp = Integer.toHexString(bytes[i] & 0xFF);
            if (temp.length() == 1) {
                stringBuffer.append("0");
            }
            stringBuffer.append(temp);
        }
        return stringBuffer.toString();
    }
}
